const { writeFile, jsonToStr, getStat, getSubPageFileName } = require('./utils')
const path = require('path')
const inquirer = require('inquirer')
const { isNotEmpty, isFileName } = require('./validate')

let subPackagesFiles = getSubPageFileName(true)
let packagesPrarentPath = ''

async function create() {
  let pageInput = await inquirer.prompt([
    {
      name: 'page',
      type: 'input',
      message: '请输入页面名称：',
      validate(val) {
        let flag = isFileName(val)
        if (flag !== true) {
          return flag
        } else {
          return isNotEmpty(val)
        }
      }
    },
    {
      name: 'pageTitle',
      type: 'input',
      message: '请输入页面标题：',
      validate: isNotEmpty
    },
    {
      name: 'packagePath',
      type: 'list',
      message: '请输入包名称(默认pages)：',
      default: 'pages',
      choices: ['pages', ...subPackagesFiles, '自定义']
    }
    // {
    //   name: 'loginRequired',
    //   type: 'confirm',
    //   message: '该页面是否需要登录?',
    //   default: false
    // },
    // {
    //   name: 'disabledShare',
    //   type: 'confirm',
    //   message: '该页面是否禁用分享?',
    //   default: false
    // }
  ])
  let packageInputQuestion = [
    {
      name: 'routerName',
      type: 'input',
      message: '路由名称(默认页面名称)：',
      default(val) {
        let defaultVal = val.packagePath || pageInput.packagePath
        return defaultVal !== 'pages'
          ? defaultVal + '-' + pageInput.page
          : pageInput.page
      },
      validate(val) {
        let flag = isFileName(val)
        if (flag !== true) {
          return flag
        } else {
          return isNotEmpty(val)
        }
      }
    }
  ]
  if (pageInput.packagePath === '自定义') {
    packageInputQuestion.unshift({
      name: 'packagePath',
      type: 'input',
      message: `请输入自定义包名称${
        packagesPrarentPath ? '(默认' + packagesPrarentPath + ')' : ''
      }：`,
      default: 'pages',
      validate(val) {
        let flag = isFileName(val)
        if (flag !== true) {
          return flag
        } else {
          return isNotEmpty(val)
        }
      }
    })
  }
  let packageInput = await inquirer.prompt(packageInputQuestion)

  let inputCfg = {
    ...pageInput,
    ...packageInput
  }
  for (let p in inputCfg) {
    if (typeof inputCfg[p] === 'string') {
      inputCfg[p] = inputCfg[p].trim()
    }
  }
  let {
    page,
    pageTitle,
    packagePath,
    routerName,
    loginRequired,
    disabledShare
  } = inputCfg
  let isSubPages = packagePath !== 'pages'
  let packagePathOrgin = packagePath
  if (isSubPages) {
    packagePath = packagesPrarentPath + packagePath
  }

  if (page) {
    let tpl = getPageTpl(page)
    let replaceAns = await inquirer.prompt([
      {
        name: 'confirmCreate',
        type: 'confirm',
        message: `页面路径：${packagePath}/${page}/${page} 页面标题：${pageTitle}`
      }
    ])
    // 确认是否覆盖
    if (replaceAns.confirmCreate) {
      writeFile(
        path.resolve(__dirname, `../src/${packagePath}/${page}/${page}.vue`),
        tpl
      )
      writeRouterConfig()
    }
  } else {
    console.log('请输入页面')
  }

  /**
   * @description: 生成路由配置
   * @param {*}
   * @return {*}
   * @author: dubangrong
   */
  async function writeRouterConfig() {
    let pagePath = `${page}/${page}`
    let pageConfig = []
    let subPageConfig = {}
    let fullPath = `../src/pages-config/sub-packages/${packagePathOrgin}.js`

    if (isSubPages) {
      let isExists = await getStat(path.resolve(__dirname, fullPath))
      if (!isExists) {
        // 创建
        await writeFile(
          path.resolve(__dirname, fullPath),
          `module.exports = ` +
            jsonToStr({
              root: packagePath,
              pages: []
            })
        )
      }
      subPageConfig = require(fullPath)
      pageConfig = subPageConfig.pages
    } else {
      fullPath = '../src/pages-config/pages.js'
      pagePath = `${packagePath}/${pagePath}`
      pageConfig = require(fullPath)
    }

    let index = pageConfig.findIndex((v) => v.path === pagePath)
    // 不存在
    if (index === -1) {
      pageConfig.push(
        getRouterTpl({
          title: pageTitle,
          name: routerName,
          path: pagePath,
          auth: loginRequired,
          disabledShare
        })
      )
    } else {
      let replaceAns = await inquirer.prompt([
        {
          name: 'confirmCreate',
          type: 'confirm',
          message: '已存在路由，是否覆盖'
        }
      ])
      // 确认是否覆盖
      if (replaceAns.confirmCreate) {
        pageConfig.splice(
          index,
          1,
          getRouterTpl({
            title: pageTitle,
            name: routerName,
            path: pagePath,
            auth: loginRequired,
            disabledShare
          })
        )
      }
    }

    writeFile(
      path.resolve(__dirname, fullPath),
      `module.exports = ` + jsonToStr(!isSubPages ? pageConfig : subPageConfig)
    )
  }
}
create()

/**
 * @description: 获取路由模板
 * @param {*} title 页面标题
 * @param {*} name 路由名称
 * @param {*} path 路径
 * @return {*}
 * @author: dubangrong
 */
function getRouterTpl({ title, name, path, auth, disabledShare }) {
  return {
    path: path,
    style: {
      navigationBarTitleText: title,
      enablePullDownRefresh: false
      //   navigationStyle: 'custom'
    },
    name: name,
    auth: auth,
    disabledShare
  }
}
/**
 * @description: 获取生成页面
 * @param {*} page 页面
 * @return {*}
 * @author: dubangrong
 */
function getPageTpl(page) {
  return `
<template>
   <ui-page ref="uiPageRef">
        <view></view>
   </ui-page>
</template>

<script setup>
// 全局onLoad,onShow
import { usePageCycle , uiPageRef} from '@/composables/global.js'
usePageCycle()


</script>

<style lang="scss" scoped>
</style>
    `
}
